// 产品出货单上传
import React, { useState, useRef } from 'react';
import useStore from '../../../components/useStore';
import { Button, Col, Divider, Empty, Row, Upload, Pagination, message, Modal, Table } from 'antd';
import store from '../../../untils/store';
import { UploadOutlined, DownloadOutlined, FileExcelOutlined, CheckOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';

const ProductDeliveryExcelForm = () => { // 通过表格批量插入出货单
    const { collapsed } = useStore();
    const { localUrl } = store();
    const fileInputRef = useRef(null);
    
    // 错误阈值设置
    const ERROR_THRESHOLD = 5;
    
    // 状态管理
    const [result, setResult] = useState([]);
    const [failurePageSize, setFailurePageSize] = useState(10);
    const [failureCurrentPage, setFailureCurrentPage] = useState(1);
    const [warningPageSize, setWarningPageSize] = useState(10);
    const [warningCurrentPage, setWarningCurrentPage] = useState(1);
    const [uploadStatus, setUploadStatus] = useState(null);
    const [checkResults, setCheckResults] = useState(null);
    const [checkModalVisible, setCheckModalVisible] = useState(false);
    const [formatErrors, setFormatErrors] = useState([]);
    const [fileSelectedKey, setFileSelectedKey] = useState(Date.now());
    const [preCheckResult, setPreCheckResult] = useState(null);
    const [isFileSelecting, setIsFileSelecting] = useState(false);

    // 上传前的本地预检
    const preCheckFile = async (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    const firstSheetName = workbook.SheetNames[0];
                    const worksheet = workbook.Sheets[firstSheetName];
                    const jsonData = XLSX.utils.sheet_to_json(worksheet, { 
                        header: 1,
                        defval: ''
                    });

                    const { results, errors } = performLocalChecks(jsonData);
                    setPreCheckResult(results);
                    
                    // 计算总错误数量
                    const totalErrors = results.duplicateDeliveryNumbers.length +
                                      results.emptyDeliveryNumbers.length +
                                      results.emptyAddresses.length +
                                      results.emptyProductNumbers.length +
                                      results.emptyRows.length;
                    
                    // 格式错误处理
                    if (errors.length > 0) {
                        message.error(`文件格式错误：${errors.join('；')}`);
                        reject(new Error('文件格式错误'));
                        return;
                    }
                    
                    // 错误阈值处理
                    if (totalErrors > ERROR_THRESHOLD) {
                        Modal.confirm({
                            title: '检测到较多错误',
                            icon: <ExclamationCircleOutlined />,
                            content: (
                                <div>
                                    <p>检测到文件中存在 {totalErrors} 个错误，超过了建议的阈值（{ERROR_THRESHOLD}个）。</p>
                                    <p>继续上传可能会导致大部分数据无法正常导入，建议先修正错误。</p>
                                </div>
                            ),
                            okText: '继续上传',
                            cancelText: '取消',
                            onOk: () => resolve(true),
                            onCancel: () => reject(new Error('用户取消上传'))
                        });
                    } else {
                        resolve(true);
                    }
                } catch (error) {
                    console.error('文件预检错误:', error);
                    message.error('文件解析失败，请检查文件格式');
                    reject(error);
                }
            };
            reader.readAsArrayBuffer(file);
        });
    };

    // 文件检查 - 增加文件类型验证和大小限制
    const check = async (file) => {
        // 1. 验证文件类型
        const fileExtension = file.name.split('.').pop().toLowerCase();
        const allowedExtensions = ['xlsx', 'xls'];
        
        if (!allowedExtensions.includes(fileExtension)) {
            message.error("请上传Excel文件（.xlsx或.xls格式）");
            setUploadStatus('error');
            return false; // 阻止上传
        }

        // 2. 验证文件大小
        if (file.size > 100 * 1024 * 1024) { // 文件大于100MB不让上传
            message.error("文件过大，不能超过100MB");
            setUploadStatus('error');
            return false; // 阻止上传
        }

        // 进行本地预检
        try {
            setUploadStatus('uploading');
            await preCheckFile(file);
            return true;
        } catch (error) {
            setUploadStatus('error');
            return false;
        }
    };

    // 处理上传结果
    const handleChange = async (res) => {
        // 处理文件类型错误或过大的情况
        if (res.file.status === "error" && res.file.error) {
            const errorMsg = res.file.error.message.includes("file too large") 
                ? "文件过大，上传已终止"
                : res.file.error.message.includes("invalid file type")
                    ? "文件类型错误，仅支持Excel文件"
                    : "上传失败，请重试";
            
            message.error(errorMsg);
            setUploadStatus('error');
            return;
        }

        if (res.file.status === "done") {
            setResult(res.file.response.data);
            // 重置分页到第一页
            setFailureCurrentPage(1);
            setWarningCurrentPage(1);
            setUploadStatus(null); // 重置上传状态
            message.success("上传成功");
        } else if (res.file.status === "removed") {
            setUploadStatus(null); // 移除文件后重置状态
        }
    };

    // 本地文件自检功能
    const handleLocalCheck = () => {
        // 重置检查相关状态
        setCheckResults(null);
        setFormatErrors([]);
        setCheckModalVisible(false);
        
        // 强制刷新文件输入，解决同一文件无法重复选择的问题
        const newKey = Date.now();
        setFileSelectedKey(newKey);
        
        // 确保状态更新完成后再触发文件选择
        setTimeout(() => {
            if (fileInputRef.current) {
                setIsFileSelecting(true);
                fileInputRef.current.click();
            }
        }, 0);
    };

    // 处理本地文件选择
    const handleFileSelect = (e) => {
        setIsFileSelecting(false);
        const file = e.target.files[0];
        if (!file) return;

        if (!checkFileValidity(file)) {
            e.target.value = '';
            return;
        }

        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];
                const jsonData = XLSX.utils.sheet_to_json(worksheet, { 
                    header: 1,
                    defval: ''
                });

                const { results, errors } = performLocalChecks(jsonData);
                setFormatErrors(errors);
                setCheckResults(results);
                
                // 确保状态更新后再显示弹窗
                setTimeout(() => {
                    setCheckModalVisible(true);
                }, 0);
            } catch (error) {
                console.error('解析Excel文件错误:', error);
                message.error('文件解析失败，请检查文件格式是否正确');
            } finally {
                // 清空文件输入，允许重新选择同一文件
                e.target.value = '';
            }
        };
        reader.readAsArrayBuffer(file);
    };

    // 验证文件有效性
    const checkFileValidity = (file) => {
        const fileExtension = file.name.split('.').pop().toLowerCase();
        const allowedExtensions = ['xlsx', 'xls'];
        
        if (!allowedExtensions.includes(fileExtension)) {
            message.error("请上传Excel文件（.xlsx或.xls格式）");
            return false;
        }

        if (file.size > 100 * 1024 * 1024) {
            message.error("文件过大，不能超过100MB");
            return false;
        }

        return true;
    };

    // 执行本地文件检查 - 实现产品出货单校验规则
    const performLocalChecks = (jsonData) => {
        const results = {
            totalRows: jsonData.length - 1,
            valid: true,
            duplicateDeliveryNumbers: [],      // 出货单号重复
            emptyDeliveryNumbers: [],          // 出货单号为空
            emptyAddresses: [],                // 送货地址为空
            emptyProductNumbers: [],           // 产品料号为空
            emptyRows: []                      // 空行
        };
        
        const formatErrors = [];

        // 检查文件是否为空
        if (jsonData.length <= 1) {
            formatErrors.push("文件内容为空或只有表头");
            results.valid = false;
            return { results, errors: formatErrors };
        }

        // 检查必要的表头
        const headers = jsonData[0].map(header => header.toString().trim());
        const deliveryNumberIndex = headers.findIndex(header => 
            header.includes('出货单号')
        );
        const addressIndex = headers.findIndex(header => 
            header.includes('送货地址')
        );
        const productNumberIndex = headers.findIndex(header => 
            header.includes('产品料号')
        );

        // 验证必要列是否存在
        if (deliveryNumberIndex === -1) {
            formatErrors.push("未找到'出货单号'列，请检查文件格式是否正确");
            results.valid = false;
        }
        
        if (addressIndex === -1) {
            formatErrors.push("未找到'送货地址'列，请检查文件格式是否正确");
            results.valid = false;
        }
        
        if (productNumberIndex === -1) {
            formatErrors.push("未找到'产品料号'列，请检查文件格式是否正确");
            results.valid = false;
        }

        if (formatErrors.length > 0) {
            return { results, errors: formatErrors };
        }

        // 检查出货单号重复和为空的情况
        const deliveryNumberMap = new Map();
        for (let i = 1; i < jsonData.length; i++) {
            const row = jsonData[i];
            const rowNumber = i + 1;
            const deliveryNumber = row[deliveryNumberIndex]?.toString().trim() || '';
            const address = row[addressIndex]?.toString().trim() || '';
            const productNumber = row[productNumberIndex]?.toString().trim() || '';
            
            // 检查出货单号是否为空
            if (!deliveryNumber) {
                results.emptyDeliveryNumbers.push({ row: rowNumber });
                results.valid = false;
            } else {
                // 检查出货单号是否重复
                if (deliveryNumberMap.has(deliveryNumber)) {
                    deliveryNumberMap.get(deliveryNumber).push(rowNumber);
                } else {
                    deliveryNumberMap.set(deliveryNumber, [rowNumber]);
                }
            }
            
            // 检查送货地址是否为空
            if (!address) {
                results.emptyAddresses.push({ row: rowNumber });
                results.valid = false;
            }
            
            // 检查产品料号是否为空
            if (!productNumber) {
                results.emptyProductNumbers.push({ row: rowNumber });
                results.valid = false;
            }
        }

        // 处理重复的出货单号
        deliveryNumberMap.forEach((rows, number) => {
            if (rows.length > 1) {
                results.duplicateDeliveryNumbers.push({
                    deliveryNumber: number,
                    rows: rows
                });
                results.valid = false;
            }
        });

        // 检查空行
        let lastDataRow = 0;
        // 从后往前找最后一行有数据的行
        for (let i = jsonData.length - 1; i >= 1; i--) {
            const row = jsonData[i];
            if (row.some(cell => cell.toString().trim() !== '')) {
                lastDataRow = i + 1;
                break;
            }
        }

        // 检查数据区域内的空行
        for (let i = 1; i < jsonData.length; i++) {
            const row = jsonData[i];
            const rowNumber = i + 1;
            
            const isEmptyRow = row.every(cell => cell.toString().trim() === '');
            
            if (isEmptyRow && rowNumber < lastDataRow) {
                results.emptyRows.push(rowNumber);
                results.valid = false;
            }
        }

        return { results, errors: formatErrors };
    };

    // 获取当前页的失败数据
    const getCurrentFailureData = () => {
        if (!result.reasons || result.reasons.length === 0) return [];
        
        const startIndex = (failureCurrentPage - 1) * failurePageSize;
        const endIndex = startIndex + failurePageSize;
        return result.reasons.slice(startIndex, endIndex);
    };

    // 获取当前页的需手动介入数据
    const getCurrentWarningData = () => {
        if (!result.warnings || result.warnings.length === 0) return [];
        
        const startIndex = (warningCurrentPage - 1) * warningPageSize;
        const endIndex = startIndex + warningPageSize;
        return result.warnings.slice(startIndex, endIndex);
    };

    // 处理失败记录分页变化
    const handleFailurePageChange = (page, pageSize) => {
        setFailureCurrentPage(page);
        setFailurePageSize(pageSize);
    };

    // 处理需手动介入记录分页变化
    const handleWarningPageChange = (page, pageSize) => {
        setWarningCurrentPage(page);
        setWarningPageSize(pageSize);
    };

    // 导出错误记录到Excel
    const exportErrorRecordsToExcel = () => {
        if (result.length === 0) {
            message.warning("没有可导出的记录");
            return;
        }

        // 检查是否有错误或需手动介入的记录
        const hasErrorRecords = (result.reasons && result.reasons.length > 0) || 
                              (result.warnings && result.warnings.length > 0);
        
        if (!hasErrorRecords) {
            message.info("没有需要纠正的错误记录");
            return;
        }

        try {
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            
            // 准备所有需要纠正的记录
            const errorRecords = [];
            // 添加标题行
            errorRecords.push(["状态", "记录所在行数", "原因"]);
            
            // 添加失败记录
            if (result.reasons && result.reasons.length > 0) {
                result.reasons.forEach(item => {
                    errorRecords.push(["失败", item.row, item.reason]);
                });
            }
            
            // 添加需手动介入记录
            if (result.warnings && result.warnings.length > 0) {
                result.warnings.forEach(item => {
                    errorRecords.push(["需手动介入", item.row, item.reason]);
                });
            }

            // 创建工作表
            const ws = XLSX.utils.aoa_to_sheet(errorRecords);
            // 调整列宽
            ws['!cols'] = [
                {wch: 12},  // 状态列宽
                {wch: 15},  // 记录所在行数列宽
                {wch: 60}   // 原因列宽（适应长文本）
            ];
            
            // 添加工作表到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "错误记录");

            // 生成精确到秒的当前时间字符串
            const now = new Date();
            const timeStr = now.toLocaleDateString().replace(/\//g, '-') + 
                          '_' + now.toTimeString().slice(0, 8).replace(/:/g, '-');
            
            // 生成文件名
            const fileName = `产品出货单错误记录_${timeStr}.xlsx`;
            
            // 导出文件
            XLSX.writeFile(wb, fileName);
            message.success("错误记录已成功导出为Excel");
        } catch (error) {
            console.error("导出Excel失败:", error);
            message.error("导出失败，请重试");
        }
    };

    // 检查结果表格的列定义
    const duplicateColumns = [
        {
            title: '出货单号',
            dataIndex: 'deliveryNumber',
            key: 'deliveryNumber',
            width: '30%',
        },
        {
            title: '重复行号',
            dataIndex: 'rows',
            key: 'rows',
            render: (rows) => rows.join(', '),
        },
    ];

    const emptyDeliveryNumberColumns = [
        {
            title: '行号',
            dataIndex: 'row',
            key: 'row',
            width: '100%',
        },
    ];

    const emptyAddressColumns = [
        {
            title: '行号',
            dataIndex: 'row',
            key: 'row',
            width: '100%',
        },
    ];

    const emptyProductNumberColumns = [
        {
            title: '行号',
            dataIndex: 'row',
            key: 'row',
            width: '100%',
        },
    ];

    return (
        <div style={{
            height: "94%",
            backgroundColor: `#F1F1F1`,
            right: "1%",
            top: "4vh",
            overflow: "hidden",
            backgroundSize: "100% 100%",
            width: collapsed ? "94%" : "84%",
            position: "absolute",
            color: "white",
            fontSize: "0.8rem"
        }}>
            <input
                type="file"
                ref={fileInputRef}
                key={fileSelectedKey}
                style={{ display: 'none' }}
                accept=".xlsx,.xls"
                onChange={handleFileSelect}
            />
            
            {/* 检查结果弹窗 */}
            <Modal
                title="本地文件检查结果"
                visible={checkModalVisible}
                onCancel={() => setCheckModalVisible(false)}
                footer={[
                    <Button key="close" onClick={() => setCheckModalVisible(false)}>
                        关闭
                    </Button>
                ]}
                width={800}
                destroyOnClose={true}
            >
                {checkResults ? (
                    <div>
                        {formatErrors.length > 0 && (
                            <div style={{ 
                                marginBottom: 16, 
                                padding: 12, 
                                backgroundColor: '#fff1f0', 
                                border: '1px solid #ffa39e',
                                borderRadius: 4
                            }}>
                                <div style={{ 
                                    display: 'flex', 
                                    alignItems: 'center',
                                    color: '#f5222d',
                                    marginBottom: 8
                                }}>
                                    <ExclamationCircleOutlined style={{ marginRight: 8 }} />
                                    <strong>文件格式错误</strong>
                                </div>
                                <ul style={{ 
                                    color: '#f5222d',
                                    paddingLeft: 24,
                                    margin: 0
                                }}>
                                    {formatErrors.map((error, index) => (
                                        <li key={index} style={{ marginBottom: 4 }}>{error}</li>
                                    ))}
                                </ul>
                                <div style={{ marginTop: 12, color: '#666', fontSize: 14 }}>
                                    请参考下载的模板文件调整表格格式后重试
                                </div>
                            </div>
                        )}

                        <div style={{ marginBottom: 16, fontSize: 16 }}>
                            {checkResults.valid ? (
                                <span style={{ color: '#52c41a' }}>
                                    <CheckOutlined /> 本地检查通过
                                </span>
                            ) : (
                                <span style={{ color: '#f5222d' }}>
                                    检查发现 {checkResults.duplicateDeliveryNumbers.length +
                                    checkResults.emptyDeliveryNumbers.length +
                                    checkResults.emptyAddresses.length +
                                    checkResults.emptyProductNumbers.length +
                                    checkResults.emptyRows.length} 个问题
                                </span>
                            )}
                        </div>
                        
                        {checkResults.valid && formatErrors.length === 0 && (
                            <div style={{
                                marginBottom: 16,
                                padding: 12,
                                backgroundColor: '#f6ffed',
                                border: '1px solid #b7eb8f',
                                borderRadius: 4,
                                color: '#52c41a',
                                fontSize: 14
                            }}>
                                <p style={{ margin: 0 }}>
                                    注意：此结果仅代表文件通过了本地格式和内容检查，
                                    不保证在上传到系统时一定能完全插入数据库。
                                </p>
                            </div>
                        )}
                        
                        <p>总数据行数: {checkResults.totalRows}</p>
                        
                        {/* 出货单号重复检查结果 */}
                        {checkResults.duplicateDeliveryNumbers.length > 0 && (
                            <div style={{ marginBottom: 24 }}>
                                <h3 style={{ color: '#f5222d', marginTop: 16 }}>
                                    出货单号重复 ({checkResults.duplicateDeliveryNumbers.length})
                                </h3>
                                <Table
                                    dataSource={checkResults.duplicateDeliveryNumbers}
                                    columns={duplicateColumns}
                                    pagination={{ pageSize: 5 }}
                                    rowKey="deliveryNumber"
                                    size="small"
                                />
                            </div>
                        )}
                        
                        {/* 出货单号为空检查结果 */}
                        {checkResults.emptyDeliveryNumbers.length > 0 && (
                            <div style={{ marginBottom: 24 }}>
                                <h3 style={{ color: '#f5222d', marginTop: 16 }}>
                                    出货单号为空 ({checkResults.emptyDeliveryNumbers.length})
                                </h3>
                                <p style={{ color: '#666', marginBottom: 8 }}>
                                    提示：出货单号为必填项，以下行号的出货单号为空，请补充完整
                                </p>
                                <Table
                                    dataSource={checkResults.emptyDeliveryNumbers}
                                    columns={emptyDeliveryNumberColumns}
                                    pagination={{ pageSize: 5 }}
                                    rowKey="row"
                                    size="small"
                                />
                            </div>
                        )}
                        
                        {/* 送货地址为空检查结果 */}
                        {checkResults.emptyAddresses.length > 0 && (
                            <div style={{ marginBottom: 24 }}>
                                <h3 style={{ color: '#f5222d', marginTop: 16 }}>
                                    送货地址为空 ({checkResults.emptyAddresses.length})
                                </h3>
                                <p style={{ color: '#666', marginBottom: 8 }}>
                                    提示：送货地址为必填项，以下行号的送货地址为空，请补充完整
                                </p>
                                <Table
                                    dataSource={checkResults.emptyAddresses}
                                    columns={emptyAddressColumns}
                                    pagination={{ pageSize: 5 }}
                                    rowKey="row"
                                    size="small"
                                />
                            </div>
                        )}
                        
                        {/* 产品料号为空检查结果 */}
                        {checkResults.emptyProductNumbers.length > 0 && (
                            <div style={{ marginBottom: 24 }}>
                                <h3 style={{ color: '#f5222d', marginTop: 16 }}>
                                    产品料号为空 ({checkResults.emptyProductNumbers.length})
                                </h3>
                                <p style={{ color: '#666', marginBottom: 8 }}>
                                    提示：产品料号为必填项，以下行号的产品料号为空，请补充完整
                                </p>
                                <Table
                                    dataSource={checkResults.emptyProductNumbers}
                                    columns={emptyProductNumberColumns}
                                    pagination={{ pageSize: 5 }}
                                    rowKey="row"
                                    size="small"
                                />
                            </div>
                        )}
                        
                        {/* 空行检查结果 */}
                        {checkResults.emptyRows.length > 0 && (
                            <div>
                                <h3 style={{ color: '#f5222d', marginTop: 16 }}>
                                    空行 ({checkResults.emptyRows.length})
                                </h3>
                                <p style={{ color: '#666', marginBottom: 8 }}>
                                    以下行号为数据区域内的空行，请删除：
                                </p>
                                <div style={{ 
                                    padding: 12, 
                                    backgroundColor: '#f9f9f9', 
                                    borderRadius: 4,
                                    wordBreak: 'break-all'
                                }}>
                                    {checkResults.emptyRows.join(', ')}
                                </div>
                            </div>
                        )}
                    </div>
                ) : (
                    <div style={{ textAlign: 'center', padding: '20px' }}>
                        正在处理文件...
                    </div>
                )}
            </Modal>

            <div style={styles.kshcontainer}>
                <div style={{
                    fontSize: "0.7rem",
                    position: "relative",
                    width: "96%",
                    marginLeft: "2%",
                    backgroundColor: "",
                    display: "flex",
                    textIndent: "1rem",
                    justifyContent: "flex-start",
                    alignContent: "flex-start",
                    flexWrap: "wrap"
                }}>
                    <div style={{ marginTop: "2vh", width: "100%", display: "flex", justifyContent: "space-between" }}>
                        <div>
                            <Button 
                                icon={<CheckOutlined />} 
                                onClick={handleLocalCheck}
                            >
                                本地自检
                            </Button>
                            
                            <Upload
                                action="/admin/excel/addProductShipmentByExcel"
                                method="POST"
                                name="file"
                                accept=".xlsx,xls"
                                maxCount={1}
                                onChange={handleChange}
                                beforeUpload={check}
                                fileList={uploadStatus === 'error' ? [] : undefined}
                                onRemove={() => setUploadStatus(null)}
                                showUploadList={{
                                    showRemoveIcon: true,
                                    showPreviewIcon: uploadStatus !== 'error'
                                }}
                                style={{ marginLeft: 16 }}
                                headers={{
                                    Authorization: `Bearer ${JSON.parse(localStorage.getItem('user')).token}`
                                }}
                            >
                                <Button icon={<UploadOutlined />}>上传</Button>
                            </Upload>
                        </div>
                        
                        <div>
                            <Button 
                                icon={<FileExcelOutlined />} 
                                style={{ marginRight: "16px" }}
                                onClick={exportErrorRecordsToExcel}
                                disabled={result.length === 0}
                            >
                                导出错误记录
                            </Button>
                            
                            <a href={`${localUrl}产品出货单表上传模版.xlsx`}>
                                <Button icon={<DownloadOutlined />}>下载模板</Button>
                            </a>
                        </div>
                    </div>

                    <Divider>导入结果</Divider>

                    {result.length === 0 ? (
                        <div style={{ width: "100%", textAlign: "center", padding: "2rem 0" }}>
                            <Empty description="等待上传表格/结果返回" />
                        </div>
                    ) : (
                        <div style={{ width: "100%" }}>
                            <Row style={{ width: "100%", marginBottom: "16px" }} gutter={[16, 16]}>
                                <Col span={8}>
                                    <div style={styles.successCard}>
                                        <div style={styles.statTitle}>完全成功</div>
                                        <div style={styles.statValue}>{result.ok}</div>
                                    </div>
                                </Col>
                                <Col span={8}>
                                    <div style={styles.errorCard}>
                                        <div style={styles.statTitle}>失败</div>
                                        <div style={styles.statValue}>{result.no}</div>
                                    </div>
                                </Col>
                                <Col span={8}>
                                    <div style={styles.warningCard}>
                                        <div style={styles.statTitle}>需手动介入</div>
                                        <div style={styles.statValue}>{result.warning}</div>
                                    </div>
                                </Col>
                            </Row>

                            {result.no > 0 ? (
                                <div style={{ marginBottom: "24px" }}>
                                    <div style={styles.sectionTitle}>失败记录</div>
                                    <div style={styles.tableContainer}>
                                        <Row style={styles.tableHeader} gutter={24}>
                                            <Col span={12}>
                                                <div style={styles.headerText}>失败记录所在行</div>
                                            </Col>
                                            <Col span={12}>
                                                <div style={styles.headerText}>失败原因</div>
                                            </Col>
                                        </Row>

                                        {getCurrentFailureData().map((item, index) => {
                                            const originalIndex = (failureCurrentPage - 1) * failurePageSize + index;
                                            return (
                                                <Row
                                                    key={`failure-${originalIndex}`}
                                                    style={{
                                                        ...styles.tableRow,
                                                        ...(originalIndex % 2 === 0 ? styles.evenRow : styles.oddRow),
                                                        borderBottom: originalIndex < result.reasons.length - 1 ? "1px solid #f0f0f0" : "none"
                                                    }}
                                                    gutter={24}
                                                >
                                                    <Col span={12}>
                                                        <div style={styles.rowNumberError}>
                                                            {item.row}
                                                        </div>
                                                    </Col>
                                                    <Col span={12}>
                                                        <div style={styles.rowReasonError}>
                                                            {item.reason}
                                                        </div>
                                                    </Col>
                                                </Row>
                                            );
                                        })}
                                    </div>

                                    {result.reasons.length > failurePageSize && (
                                        <div style={styles.paginationContainer}>
                                            <Pagination
                                                current={failureCurrentPage}
                                                pageSize={failurePageSize}
                                                total={result.reasons.length}
                                                onChange={handleFailurePageChange}
                                                showSizeChanger
                                                showQuickJumper
                                                showTotal={(total) => `共 ${total} 条失败记录`}
                                                pageSizeOptions={['10', '20', '50', '100']}
                                            />
                                        </div>
                                    )}
                                </div>
                            ) : (
                                <div style={styles.noDataMessage}>
                                    没有失败记录
                                </div>
                            )}

                            {result.warning > 0 ? (
                                <div>
                                    <div style={styles.sectionTitle}>需手动介入记录</div>
                                    <div style={styles.tableContainer}>
                                        <Row style={styles.tableHeader} gutter={24}>
                                            <Col span={12}>
                                                <div style={styles.headerText}>需手动介入记录所在行</div>
                                            </Col>
                                            <Col span={12}>
                                                <div style={styles.headerText}>需手动介入原因</div>
                                            </Col>
                                        </Row>

                                        {getCurrentWarningData().map((item, index) => {
                                            const originalIndex = (warningCurrentPage - 1) * warningPageSize + index;
                                            return (
                                                <Row
                                                    key={`warning-${originalIndex}`}
                                                    style={{
                                                        ...styles.tableRow,
                                                        ...(originalIndex % 2 === 0 ? styles.evenRow : styles.oddRow),
                                                        borderBottom: originalIndex < result.warnings.length - 1 ? "1px solid #f0f0f0" : "none"
                                                    }}
                                                    gutter={24}
                                                >
                                                    <Col span={12}>
                                                        <div style={styles.rowNumberWarning}>
                                                            {item.row}
                                                        </div>
                                                    </Col>
                                                    <Col span={12}>
                                                        <div style={styles.rowReasonWarning}>
                                                            {item.reason}
                                                        </div>
                                                    </Col>
                                                </Row>
                                            );
                                        })}
                                    </div>

                                    {result.warnings.length > warningPageSize && (
                                        <div style={styles.paginationContainer}>
                                            <Pagination
                                                current={warningCurrentPage}
                                                pageSize={warningPageSize}
                                                total={result.warnings.length}
                                                onChange={handleWarningPageChange}
                                                showSizeChanger
                                                showQuickJumper
                                                showTotal={(total) => `共 ${total} 条需手动介入记录`}
                                                pageSizeOptions={['10', '20', '50', '100']}
                                            />
                                        </div>
                                    )}
                                </div>
                            ) : (
                                <div style={styles.noDataMessage}>
                                    没有需手动介入的记录
                                </div>
                            )}

                            {result.ok > 0 && result.no === 0 && result.warning === 0 && (
                                <div style={styles.successMessage}>
                                    全部数据导入成功！
                                </div>
                            )}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

export default ProductDeliveryExcelForm;

const styles = {
    kshcontainer: {
        width: "98%",
        height: "95%",
        position: "absolute",
        top: "3%",
        left: "1%",
        backgroundColor: "white",
        color: "black",
        borderRadius: "10px",
        overflowY: "auto",
        paddingBottom: "20px"
    },
    successCard: {
        background: "#f0f9eb",
        padding: "16px",
        borderRadius: "8px",
        boxShadow: "0 2px 4px rgba(0,0,0,0.05)",
        borderLeft: "4px solid #52c41a"
    },
    errorCard: {
        background: "#fff1f0",
        padding: "16px",
        borderRadius: "8px",
        boxShadow: "0 2px 4px rgba(0,0,0,0.05)",
        borderLeft: "4px solid #f5222d"
    },
    warningCard: {
        background: "#fffbe6",
        padding: "16px",
        borderRadius: "8px",
        boxShadow: "0 2px 4px rgba(0,0,0,0.05)",
        borderLeft: "4px solid #faad14"
    },
    statTitle: {
        color: "#1f2329",
        fontSize: "14px",
        marginBottom: "8px"
    },
    statValue: {
        fontSize: "24px",
        fontWeight: "600"
    },
    sectionTitle: {
        fontSize: "16px",
        color: "#1f2329",
        margin: "24px 0 12px",
        fontWeight: "500"
    },
    tableContainer: {
        borderRadius: "8px",
        overflow: "hidden",
        border: "1px solid #f0f0f0"
    },
    tableHeader: {
        width: "100%",
        background: "#fafafa",
        padding: "12px 16px",
        borderBottom: "1px solid #f0f0f0"
    },
    headerText: {
        color: "#1f2329",
        fontWeight: "500"
    },
    tableRow: {
        width: "100%",
        padding: "12px 16px"
    },
    evenRow: {
        background: "#fff"
    },
    oddRow: {
        background: "#fafafa"
    },
    rowNumberError: {
        display: "inline-block",
        width: "28px",
        height: "28px",
        lineHeight: "28px",
        textAlign: "center",
        borderRadius: "50%",
        background: "#fff1f0",
        color: "#f5222d",
        marginRight: "8px",
        fontWeight: "500"
    },
    rowNumberWarning: {
        display: "inline-block",
        width: "28px",
        height: "28px",
        lineHeight: "28px",
        textAlign: "center",
        borderRadius: "50%",
        background: "#fffbe6",
        color: "#faad14",
        marginRight: "8px",
        fontWeight: "500"
    },
    rowReasonError: {
        color: "#f5222d",
        lineHeight: "1.5",
        wordBreak: "break-word",
        padding: "4px 0"
    },
    rowReasonWarning: {
        color: "#faad14",
        lineHeight: "1.5",
        wordBreak: "break-word",
        padding: "4px 0"
    },
    paginationContainer: {
        marginTop: "16px",
        textAlign: "right",
        padding: "8px 0"
    },
    successMessage: {
        textAlign: "center",
        padding: "2rem",
        color: "#52c41a",
        fontSize: "16px"
    },
    noDataMessage: {
        textAlign: "center",
        padding: "1rem",
        color: "#8c8c8c",
        fontSize: "14px",
        fontStyle: "italic"
    }
};
    